JavaScript provides various operators to perform different types of operations. These include arithmetic, assignment, comparison, logical, and more.
Arithmetic operators are used to perform arithmetic on numbers:
let a = 5;
let b = 2;
let sum = a + b; // Addition
let difference = a - b; // Subtraction
let product = a * b; // Multiplication
let quotient = a / b; // Division
let remainder = a % b; // Modulus
let exponent = a ** b; // Exponentiation (ES2016)
Assignment operators assign values to variables:
let x = 10; // Assignment
x += 5; // Addition assignment
x -= 3; // Subtraction assignment
x *= 2; // Multiplication assignment
x /= 4; // Division assignment
x %= 2; // Modulus assignment
x **= 3; // Exponentiation assignment
Comparison operators compare two values and return a boolean result:
let x = 5;
let y = 10;
console.log(x == y); // Equal to
console.log(x === y); // Equal value and equal type
console.log(x != y); // Not equal
console.log(x !== y); // Not equal value or not equal type
console.log(x > y); // Greater than
console.log(x < y); // Less than
console.log(x >= y); // Greater than or equal to
console.log(x <= y); // Less than or equal to
Logical operators are used to combine conditional statements:
let a = true;
let b = false;
console.log(a && b); // Logical AND
console.log(a || b); // Logical OR
console.log(!a); // Logical NOT
Bitwise operators perform operations on binary representations of numbers:
let x = 5; // 0101 in binary
let y = 3; // 0011 in binary
console.log(x & y); // AND
console.log(x | y); // OR
console.log(x ^ y); // XOR
console.log(~x); // NOT
console.log(x << 1); // Left shift
console.log(x >> 1); // Right shift
The ternary operator is a shorthand for an if-else statement:
let age = 18;
let canVote = (age >= 18) ? "Yes" : "No";
console.log(canVote); // Outputs: Yes